---
title: "Python中的Property"
categories:
- python
tags:
---

<div id="content">
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org12c7e9e">Python Property</a>
<ul>
<li><a href="#orgdfe6859">Quick Referece</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="outline-2" id="outline-container-org12c7e9e">
<h2 id="org12c7e9e">Python Property</h2>
<div class="outline-text-2" id="text-org12c7e9e">
<p>
使用内置函数proerty，实现与C#中属性类似的功能。内置函数proerty的声明如下：
</p>
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">class</span> <span style="font-weight: bold; text-decoration: underline;">property</span>([fget[, fset[, fdel[, doc]]]])
- fget: function of getter
- fset: function of setter
- fdel: function to delete
- doc: documention of this <span style="font-weight: bold;">property</span>
</pre>
</div>
</div>
<div class="outline-3" id="outline-container-orgdfe6859">
<h3 id="orgdfe6859">Quick Referece</h3>
<div class="outline-text-3" id="text-orgdfe6859">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">class</span> <span style="font-weight: bold; text-decoration: underline;">MyClass</span>(<span style="font-weight: bold;">object</span>):
    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">__init__</span>(<span style="font-weight: bold;">self</span>):
        <span style="font-weight: bold;">self</span>._name = <span style="font-weight: bold; text-decoration: underline;">None</span>

    <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">define getter, setter, deleter</span>
    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">getname</span>(<span style="font-weight: bold;">self</span>):
        <span style="font-weight: bold;">return</span> <span style="font-weight: bold;">self</span>._name
    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">setname</span>(<span style="font-weight: bold;">self</span>, value):
        <span style="font-weight: bold;">self</span>._name = value
    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">delname</span>(<span style="font-weight: bold;">self</span>):
        <span style="font-weight: bold;">del</span> <span style="font-weight: bold;">self</span>._name

    <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">Create property</span>
    <span style="font-weight: bold; font-style: italic;">Name</span> = <span style="font-weight: bold;">property</span>(getname, setname, delname, <span style="font-style: italic;">"The Name"</span>)
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="status" id="postamble">
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
